package cat200;

import javax.swing.*;
import java.text.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import java.util.Calendar;
import java.util.GregorianCalendar;  
/**
 *
 * @author peichia
 */
public class cashPayment extends javax.swing.JFrame {
	
	Timer timer = new Timer (4000, new TimerListener());
	
	private static String dbURL = "jdbc:derby://localhost:1527/sample;create=true;user=app;password=app";   
    private static Connection conn = null;
    private static Statement stmt = null;
    DecimalFormat dp = new DecimalFormat("#0.00");
    
    private static boolean isMember = false;
    private static Double totalAmt = 0.00;
    private static String Amt = "";
 
   private static int count1;
   private static int count2;
    

    /** Creates new form cashPayment */
    public cashPayment() {
    	super("Cash Payment");
        initComponents();
        setLocationRelativeTo(null);
        createConnection();
        update();
        setTimer();
        readData();
        jProgressBar1.setVisible(false);
        jTextField2.setEditable(false);
        
    }
    
    private static void createConnection()
    {
        try
        {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            //Get a connection
            conn = DriverManager.getConnection(dbURL); 
        }
        catch (Exception except)
        {
            except.printStackTrace();
        }
    }
    
    private ResultSet getResultSet(String doubt)
    {
        createConnection();
        ResultSet outcome = null;
        try
        {
            stmt = conn.createStatement();
            outcome = stmt.executeQuery(doubt);
        }
        catch (SQLException ex)
        {
        	ex.printStackTrace();
        }
        return outcome;
    }
    
    public void readData(){
    	
    	String Amt = "";
    	
    	 createConnection();
    	 
    	  String queryString;
    	    queryString = "SELECT SUM(TEMP_LPRICE) AS TOTAL FROM APP.TEMP";

    	   ResultSet achieve = getResultSet(queryString);
    	   System.out.println(achieve);

           try
           {
           	  if (achieve.next()) 
           	  {
           		totalAmt = achieve.getDouble("TOTAL");
                System.out.println(totalAmt);
                Amt = dp.format(totalAmt);
            	total.setText(Amt);
           	  }


           }
           catch (SQLException sqlExcept)
           {
               sqlExcept.printStackTrace();
           }
           
    	 
try
{
	System.out.println("success");
    int col0,col1,col4;
    String col2;
    double col3,col5,col6;
    
    
    String queryString1;
    queryString1 = "SELECT TEMP_CODE,TEMP_NAME,TEMP_UNIT,TEMP_WEIGHT,TEMP_PRICE,TEMP_LPRICE FROM APP.TEMP ORDER BY TEMP_CODE";

    ResultSet rset = getResultSet(queryString1);

    int i = 0;
    String price;
    while(rset.next())
    {
    	col0 = i+1;
    	table.setValueAt(col0, i, 0);
        col1 = rset.getInt(1);
        table.setValueAt(col1, i, 1);
        col2 = rset.getString(2);
        table.setValueAt(col2, i, 2);
        col4 = rset.getInt(3);
        table.setValueAt(col4, i, 4);
        col3 = rset.getDouble(4);
        table.setValueAt(col3, i, 3);
        col5 = rset.getDouble(5);
        price = dp.format(col5);
        table.setValueAt(price, i, 5);
        col6 = rset.getDouble(6);
        price = dp.format(col6);
        table.setValueAt(price, i, 6);
        i++;
    }
    conn.close();
}
catch(Exception e)
{
    System.out.println("ERROR : " + e.getMessage());
    e.printStackTrace();
}    	

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        total = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cashPay = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jCheckBox1 = new javax.swing.JCheckBox();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        change = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        date = new javax.swing.JLabel();
        pay = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Num", "Code", "Name", "Weight ", "Qty", "Price (RM)", "Amt (RM)"
            }
        ));
        jScrollPane1.setViewportView(table);
        table.getColumnModel().getColumn(0).setPreferredWidth(50);
        table.getColumnModel().getColumn(1).setPreferredWidth(60);
        table.getColumnModel().getColumn(2).setPreferredWidth(150);
        table.getColumnModel().getColumn(4).setPreferredWidth(45);

        jLabel2.setText("Total Amount   : RM");

        jLabel3.setText("Cash Received : RM");

        cashPay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cashPayActionPerformed(evt);
            }
        });
        cashPay.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cashPayKeyPressed(evt);
            }
        });

        jLabel5.setText("Change             : RM");

        jCheckBox1.setText("Member");

        jButton2.setText("Enter");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel4.setText("Member's Name :");

        jLabel6.setText("Date :");

        pay.setText("PAY");
        pay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                payActionPerformed(evt);
            }
        });

        jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "CASH PAYMENT", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 3, 24), new java.awt.Color(44, 42, 225))); // NOI18N

        //jLabel7.setFont(new java.awt.Font("DejaVu Sans", 1, 18)); // NOI18N
        //jLabel7.setForeground(new java.awt.Color(193, 11, 209));
        jLabel7.setText("If is a member, please enter member id.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(change, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(cashPay)
                            .addComponent(total, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pay, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(90, 90, 90))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(251, 251, 251)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 623, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(17, 17, 17)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabel6))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jCheckBox1)
                                        .addGap(18, 18, 18)
                                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel4)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(date, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE))))))
                .addContainerGap(41, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 683, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(90, 90, 90)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(69, 69, 69)
                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCheckBox1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(total, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cashPay, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pay))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                    .addComponent(change, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(22, 22, 22))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(20, 20, 20)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
                    .addContainerGap()))
        );

        pack();
    }// </editor-fold>

    private void cashPayActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    	
    	 System.out.println("success");
    	 createConnection();
    	 
    	  String query;
    	    query = "SELECT SUM(TEMP_LPRICE) AS TOTAL FROM APP.TEMP";

    	   ResultSet rset = getResultSet(query);
    	   System.out.println(rset);

           try
           {
           	  if (rset.next()) 
           	  {
           		totalAmt = rset.getDouble("TOTAL");
           	  }


           }
           catch (SQLException sqlExcept)
           {
               sqlExcept.printStackTrace();
           }
    	
    	String memberId = jTextField1.getText();
        String queryString;
        String memberName = "";
        jTextField2.setText(memberName);

        queryString = "SELECT MEM_NAME FROM APP.MEMBER WHERE MEM_ID ="+memberId+"";

        System.out.println(queryString);
        ResultSet achieve = getResultSet(queryString);

            try
            {
            	  if (achieve.next()) 
            	  {
            		 memberName = (achieve.getString(1));
         
            	  }


            }
            catch (SQLException sqlExcept)
            {
                sqlExcept.printStackTrace();
            }
            
            if (!memberName.equals(""))
            {
            jTextField2.setText(memberName);
            isMember = true;
            }
            
            else
            {
            	 JOptionPane.showMessageDialog(null, "INVALID MEMBER ID!");
            	 jTextField1.setText("-");
            	 isMember = false;
            }
            
            if (isMember==true)
            {
            	total.setText("");
            	Amt = dp.format(0.9*totalAmt);
            	total.setText(Amt);
            	isMember = false;
            }
            
            else
            { 
            	total.setText("");
            	Amt = dp.format(totalAmt);
            	total.setText(Amt);
            	isMember = false;
            	
            }	
    }                                        

    private void cashPayKeyPressed(java.awt.event.KeyEvent evt) {                                   
        // TODO add your handling code here:
    }                                  

    private void payActionPerformed(java.awt.event.ActionEvent evt) { 
    	
    	String c = "";
    	String sTotal = "";
    	String id = " ";
    	
    	String pay = cashPay.getText();
    	
    	if (pay.equals(""))
    	{
    		JOptionPane.showMessageDialog(null, "ERROR! CASH PAID CAN'T BE NULL");
    	}
    	
    	else
    	{
    	Amt = total.getText();
    	Double payment = Double.parseDouble(String.valueOf(pay));
    	Double Amount = Double.parseDouble(String.valueOf(Amt));
    	
    	Double change1 = payment - Amount;
    	
    	if (change1<0){
    		JOptionPane.showMessageDialog(null, "INVALID AMOUNT OF CASH PAID!");
    	}
    	
    	else{
    	change.setText(dp.format(change1));
    	
   	try
   	{
   	  	String sql;
   	    sql = "SELECT SALES_NUM FROM APP.SALES WHERE SALES_NUM >= ALL(SELECT SALES_NUM FROM APP.SALES)";
   	    
   	   ResultSet rset = getResultSet(sql);
   	    while(rset.next())
   	    {
   	    	count1 = rset.getInt(1);
   	    	count1++;
   	    }
   	    conn.close();
   	}
   	catch(Exception e)
   	{
   	    System.out.println("ERROR : " + e.getMessage());
   	    e.printStackTrace();
   	}    	

   	c = Integer.toString(count1);
   	
    Calendar cal = new GregorianCalendar();
    int month = cal.get(Calendar.MONTH);
    int year = cal.get(Calendar.YEAR);
    int day = cal.get(Calendar.DAY_OF_MONTH);
    System.out.println("Current date : " + day + "/" + (month + 1) + "/" + year);
    String m = Integer.toString(month+1);
    String y = Integer.toString(year);
    String d = Integer.toString(day);
    date.setText(d + "/" + m + "/" +y+"");
    
    String dat = y+"-"+m+"-"+d;
    
    sTotal = total.getText();
    
    if (jTextField1.getText().isEmpty())
    	id = "0";
    
    else
    	id = jTextField1.getText();
    
    
    try
   	{
   		createConnection();
   		
   		stmt = conn.createStatement();
   		String sql1;
   	    sql1 = "INSERT INTO SALES VALUES (" +count1+",'"+dat+"', "+sTotal+", "+id+")";
   	    stmt.executeUpdate(sql1);
        
   	}
   	catch(Exception e)
   	{
   	    System.out.println("ERROR : " + e.getMessage());
   	    e.printStackTrace();
   	}    	
   	
	
   	
   	//delete temp table after payment
   	try
   	{
   		createConnection();
   		
   		stmt = conn.createStatement();
   		String sql1;
   	    sql1 = "DELETE FROM TEMP";
   	    stmt.executeUpdate(sql1);
        
   	}
   	catch(Exception e)
   	{
   	    System.out.println("ERROR : " + e.getMessage());
   	    e.printStackTrace();
   	}    	

          jProgressBar1.setValue(100);
          jProgressBar1.setString("Printing...");
          jProgressBar1.setStringPainted(true);
          jProgressBar1.setVisible(true);
          jProgressBar1.setIndeterminate(true);
          
          timer.start();
    	}//end if-else
    	}
    }                                   

    public void setTimer() {
        int messageTimeout = 1000;
        timer1 = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                update();
            }

        });
        timer1.restart();
    }

    public void update() {
        Date currentTime = new Date();

        time++;
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy  hh:mm:ss");
        String dateString = formatter.format(currentTime);

        date.setText(dateString);
        //JOptionPane.showMessageDialog(null, "test3");
    }
    public int time = 0;
    public Timer timer1;
    
    public void stop_timer() {
	    this.setVisible(false);
    	timer.stop();
    }
    private class TimerListener implements ActionListener{
 	   public void actionPerformed(ActionEvent e){
 		   
 	    new Main(Main.col1).setVisible(true);
 	    stop_timer();
 	   } 
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new cashPayment().setVisible(true);
               
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JTextField cashPay;
    private javax.swing.JLabel change;
    private javax.swing.JLabel date;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JButton pay;
    private javax.swing.JTable table;
    private javax.swing.JLabel total;
    // End of variables declaration

}
